<template>
	<view class="login-page">
		<!-- 顶部背景与欢迎区 -->
		<view class="top-section">
			<image src="/static/images/组 8.png" class="top-bg" mode="widthFix" />
			<text class="greeting">您好，</text>
			<text class="welcome-text">欢迎登录车联网服务！</text>
			<image src="/static/images/组 6.png" class="illustration" mode="widthFix" />
		</view>

		<!-- 登录表单 -->
		<view class="form-area">
			<input type="text" v-model="username" placeholder="手机号登录" class="input-phone" />
			<view class="verify-row">
				<input type="text" v-model="code" placeholder="输入验证码" class="input-verify" />
				<button class="get-verify-btn" @click="toGetCode()"
					:disabled="countdown>0">{{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}</button>
			</view>
			<button class="login-btn" @click="toIndex">登录</button>
		</view>

		<!-- 位置授权提示框（默认隐藏，授权时显示） -->
		<view class="location-modal" v-show="showLocationModal">
			<view class="modal-content">
				<text class="modal-title">获取你的位置信息</text>
				<text class="modal-desc">你的位置信息将用于获取你附近的站点</text>
				<view class="modal-btns">
					<button class="reject-btn" @click="rejectLocation">拒绝</button>
					<button class="allow-btn" @click="allowLocation">允许</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		get,
		post
	} from '@/utils/request.js'
	export default {
		data() {
			return {
				showLocationModal: false, // 控制位置提示框的显示/隐藏
				username: '', // 手机号
				code: '', // 验证码
				countdown: 0, //验证码倒计时
			}
		},
		onShow() {
			// 页面显示时，检查位置授权状态
			this.checkLocationAuthorization();
			this.uploadLocationToServer();
		},
		methods: {
			toIndex() {
				if (this.code == '' || this.username == '' || this.username.length != 11) {
					uni.showToast({
						title: "手机号/验证码不完整",
						icon: 'error',
						duration: 3000
					})
					return;
				}
				console.log("点击了登录");
				var login = {
					username: '',
					code: ''
				}
				login.username = this.username
				login.code = this.code


				post("/auth/login2", login).then(resp => {
					console.log(resp);
					if (resp.code === 200) {
						uni.showToast({
							title: resp.msg,
							icon: 'success',
							duration: 1500,
							mask:true
						})
						uni.setStorageSync('token', resp.data.access_token)

						


						setTimeout(() => {
							uni.switchTab({
								url: '/pages/index/index'
							});
						}, 1500); 
					}else{
						console.log("没有权限登录");
						uni.showToast({
							title:resp.msg,
							icon:'error',
							duration:1000
						})
						this.code=''
					}

				})

			},
			// 检查位置授权状态
			checkLocationAuthorization() {
				uni.getSetting({
					success: (res) => {
						// 未请求过位置授权，或曾拒绝过授权 → 显示提示框
						if (
							res.authSetting['scope.userLocation'] === undefined ||
							res.authSetting['scope.userLocation'] === false
						) {
							this.showLocationModal = true;
						}
					},
					fail: (err) => {
						console.error('获取设置失败', err);
					}
				});
			},

			// 拒绝位置授权
			rejectLocation() {
				this.showLocationModal = false;
				// 可在此添加“拒绝后”的业务逻辑（如后续无法获取附近站点）
			},

			// 允许位置授权
			allowLocation() {
				uni.authorize({
					scope: 'scope.userLocation', // 位置授权标识
					success: () => {
						this.showLocationModal = false;
						// 授权成功后，获取具体位置信息
						uni.getLocation({
							type: 'wgs84', // 坐标类型（可根据需求选 gcj02）
							success: (locationRes) => {
								console.log('位置信息：', locationRes); // 经纬度等信息
								uni.setStorageSync('userLocation', locationRes);
								console.log('本地存储的位置信息：', uni.getStorageSync('userLocation'));
							},
							fail: (err) => {
								console.error('获取位置失败', err);
							}
						});
					},
					fail: (err) => {
						console.error('授权失败', err);
						this.showLocationModal = false;
						// 可提示用户"前往设置开启位置权限"
					}
				});
			},
			
			// 上传位置信息到后端
			uploadLocationToServer() {
				const userLocation = uni.getStorageSync('userLocation');
				
				const locationInfo = {
					latitude: userLocation?.latitude || 0,
					longitude: userLocation?.longitude || 0
				};
				
				post('/user/user/update', locationInfo)
					.then(res => {
						if (res.code === 200) {
							console.log('位置信息上传成功:', res);
						} else {                                                                       
							console.error('位置信息上传失败:', res.msg);
						}
					})
					.catch(error => {
						console.error('位置信息上传异常:', error);
					});
			},
			
			toGetCode() {

				// 首先判断手机号是否正确
				var isTel = this.validatePhone(this.username)

				if (!isTel.valid) {
					uni.showToast({
						title: isTel.message,
						icon: 'error',
						duration: 1500
					});

				} else {

					this.countdown = 60;
					const timer = setInterval(() => {
						this.countdown--;
						// 倒计时结束，清除定时器
						if (this.countdown <= 0) {
							clearInterval(timer);
						}
					}, 1000);
					get("/auth/code3", {
						"username": this.username
					}).then(resp => {
						console.log(resp);
						if (resp.code === 200) {
							uni.showToast({
								title: resp.data + " " + resp.msg,
								icon: 'success',
								duration: 5000
							})
						} else {
							uni.showToast({
								title: resp.msg,
								icon: 'error',
								duration: 3000
							})
							clearInterval(timer);
						}

					}).catch(error => {
						console.log(error);
						uni.showToast({
							title: error.msg,
							icon: 'error',
							duration: 3000
						})
					})

				}

			},


			// 验证手机号
			validatePhone(phone) {
				// 去除空格
				const phoneNum = phone.replace(/\s+/g, '');
				// 1. 检查是否为空
				if (!phoneNum) {
					return {
						valid: false,
						message: '请输入手机号码'
					};
				}
				// 2. 检查长度是否为11位
				if (phoneNum.length !== 11) {
					return {
						valid: false,
						message: '请输入11位手机号码'
					};
				}
				const reg = /^1[3-9]\d{9}$/;
				if (!reg.test(phoneNum)) {
					return {
						valid: false,
						message: '请输入正确的手机号码'
					};
				}

				return {
					valid: true,
					message: '验证通过'
				};
			},
		}
	}
</script>

<style>
	.login-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	/* 顶部背景与欢迎区 */
	.top-section {
		position: relative;
		width: 100%;
	}

	.top-bg {
		width: 100%;
	}

	.greeting,
	.welcome-text {
		position: absolute;
		left: 40rpx;
		color: #ffffff;
	}

	.greeting {
		top: 120rpx;
		font-size: 36rpx;
	}

	.welcome-text {
		top: 180rpx;
		font-size: 28rpx;
	}

	.illustration {
		position: absolute;
		right: 40rpx;
		top: 200rpx;
		width: 240rpx;
	}

	/* 登录表单 */
	.form-area {
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.input-phone,
	.input-verify {
		width: 100%;
		height: 80rpx;
		border-bottom: 1rpx solid #eee;
		margin-bottom: 30rpx;
		padding-left: 20rpx;
		box-sizing: border-box;
	}

	.verify-row {
		width: 100%;
		display: flex;
		align-items: center;
		margin-bottom: 60rpx;
	}

	.input-verify {
		flex: 1;
		margin-bottom: 0;
	}

	.get-verify-btn {
		font-size: 20rpx;
		line-height: 60rpx;
		width: 200rpx;
		height: 60rpx;
		background-color: #2176F3;
		color: #fff;
		border-radius: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.login-btn {
		width: 100%;
		height: 80rpx;
		background-color: #2176F3;
		color: #fff;
		border-radius: 40rpx;
		font-size: 32rpx;
	}

	/* 位置授权提示框 */
	.location-modal {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top-left-radius: 30rpx;
		border-top-right-radius: 30rpx;
		padding: 40rpx;
		box-shadow: 0 -5rpx 15rpx rgba(0, 0, 0, 0.1);
	}

	.modal-content {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.modal-desc {
		font-size: 26rpx;
		color: #666666;
		margin-bottom: 40rpx;
		text-align: center;
	}

	.modal-btns {
		display: flex;
		width: 100%;
		justify-content: space-between;
	}

	.reject-btn,
	.allow-btn {
		width: 300rpx;
		height: 80rpx;
		border-radius: 40rpx;
	}

	.reject-btn {
		background-color: #eeeeee;
		color: #666666;
	}

	.allow-btn {
		background-color: #2176F3;
		color: #ffffff;
	}
</style>